package com.dreamfire.display.display2D
{
	import com.dreamfire.asset.AssetManager;
	import com.dreamfire.display.display2D.core.ISprite2D;
	import com.dreamfire.display.display2D.core.Sprite2D;
	import com.dreamfire.display.display2D.core.Tile2D;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Shape;
	import flash.display.Sprite;
	import flash.geom.Vector3D;
	import flash.utils.Dictionary;

	public class Viewport2D extends Sprite
	{
		//----------------------------------------------------------------------------------------
		//
		//  Variable
		//
		//----------------------------------------------------------------------------------------
		private var _scene:Scene2D = null;
		private var _camera:Camera2D = null;
		
		private var _mask:Shape = null;
		
		private var _spriteInstanceList:Dictionary = null;
		private var _spriteContainer:Sprite = null;
		
		private var _map:Bitmap = null;
		private var _mapBuff:BitmapData = null;//后台缓冲
		
		private var _size:uint = 32;
		
		//----------------------------------------------------------------------------------------
		//
		//  Setter & Getter
		//
		//----------------------------------------------------------------------------------------
		public function get scene():Scene2D
		{
			return _scene;
		}
		
		public function get camera():Camera2D
		{
			return _camera;
		}
		
		//----------------------------------------------------------------------------------------
		//
		//  Constructor
		//
		//----------------------------------------------------------------------------------------
		public function Viewport2D(width:Number, height:Number, scene:Scene2D = null, camera:Camera2D = null, size:uint = 32)
		{
			_scene = scene || new Scene2D();
			_camera = camera || new Camera2D(width, height, _scene, this, new Vector3D(), size);
			
			_mapBuff = new BitmapData(_camera.width + _camera.width * .5, _camera.height + _camera.height * .5);
			_map = new Bitmap(_mapBuff);
			this.addChild(_map);
			
			_spriteInstanceList = new Dictionary(true);
			_spriteContainer = new Sprite();
			this.addChild(_spriteContainer);
		}
		
		//----------------------------------------------------------------------------------------
		//
		//  Performance
		//
		//----------------------------------------------------------------------------------------
		public function render():void
		{
			_camera.update();
			
			spriteRender();
			mapRender();
		}
		
		private function spriteRender():void
		{
			//渲染镜头精灵列表中所有的精灵
			_spriteContainer.removeChildren();
			for each( var sp:Sprite2D in _camera.spriteList )
			{
				if( sp )
					_spriteContainer.addChild( sp );
			}
		}
		
		private function mapRender():void
		{
			//渲染镜头地图列表中所有的地图瓦片
			_map.bitmapData = camera.getMapBmp();
		}
	}
}